﻿namespace TanHungViet.Web.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using log4net;
    using TanHungViet.Helper;

    public class MenuRepository
    {
        private static ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private DBTanHungVietEntities _db;

        public MenuRepository(DBTanHungVietEntities entity)
        {
            _db = entity;
        }

        public string GetMenuTitle(int menuID, string cultureInfo)
        {
            try
            {
                var language = _db.Language.FirstOrDefault(b => b.LanguageCode.Equals(cultureInfo));
                if (language == null)
                {
                    _logger.Warn("Language is null");
                    return string.Empty;
                }

                var menuDetail = _db.MenuDetail.FirstOrDefault(b => b.MenuID == menuID && b.LanguageID == language.LanguageID);
                if (menuDetail == null)
                {
                    _logger.Warn("Cannot find menu title!");
                    return string.Empty;
                }

                return menuDetail.MenuTitle;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }

        public List<MenuItem> GetDynamicMenu(string cultureInfo, bool isVertical)
        {
            try
            {
                List<MenuItem> result = new List<MenuItem>();
                var verticalMenu = from b in _db.Menu
                                   where b.IsVertical == isVertical && b.ParentID == 0
                                   orderby b.MenuOrder
                                   select b;

                foreach (var item in verticalMenu)
                {
                    MenuItem menuItem = new MenuItem();
                    menuItem.Link = item.MenuLink;
                    menuItem.Title = GetMenuTitle(item.MenuID, cultureInfo);
                    menuItem.ContentID = item.ContentID ?? 0;
                    if (menuItem.ContentID != 0)
                    {
                        var content = _db.Content.FirstOrDefault(b => b.ContentID == menuItem.ContentID);
                        if (content == null)
                        {
                            _logger.WarnFormat("Cannot find content with id = {0}!", content.ContentID.ToString());
                            menuItem.Code = string.Empty;
                        }
                        else
                            menuItem.Code = content.ContentCode;
                    }
                    else
                        menuItem.Code = string.Empty;



                    var subMenu = from b in _db.Menu
                                  where b.ParentID == item.MenuID
                                  orderby b.MenuOrder
                                  select b;
                    if (subMenu != null)
                    {
                        menuItem.SubMenu = new List<MenuItem>();
                        foreach (var subItem in subMenu)
                        {
                            MenuItem subMenuItem = new MenuItem();
                            subMenuItem.Link = subItem.MenuLink;
                            subMenuItem.Title = GetMenuTitle(subItem.MenuID, cultureInfo);
                            subMenuItem.ContentID = subItem.ContentID ?? 0;
                            if (subMenuItem.ContentID != 0)
                            {
                                var content = _db.Content.FirstOrDefault(b => b.ContentID == subMenuItem.ContentID);
                                if (content == null)
                                {
                                    _logger.WarnFormat("Cannot find content with id = {0}!", content.ContentID.ToString());
                                    subMenuItem.Code = string.Empty;
                                }
                                else
                                    subMenuItem.Code = content.ContentCode;
                            }
                            else
                                subMenuItem.Code = string.Empty;

                            menuItem.SubMenu.Add(subMenuItem);
                        }
                    }

                    result.Add(menuItem);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }

        public void AddNewMenu(string title, string parentCode)
        {
            try
            {
                Content parentContent = _db.Content.FirstOrDefault(b => b.ContentCode == parentCode);
                if (parentCode == null)
                    return;
                string code = TanHungViet.Helper.Util.GenerateCodeByTitle(title.Trim().ToLower());

                Content newContent = new Content();
                newContent.ContentParent = parentContent.ContentID;
                // check content code if it's exist
                ContentRepository contentRepository = new ContentRepository(_db);
                bool checkExistCode = true;
                do
                {
                    Content checkContent = contentRepository.GetContentByCode(code);
                    if (checkContent != null)
                    {
                        code += "-1";
                        _logger.InfoFormat("New content code is ({0})", code);
                    }
                    else
                        checkExistCode = false;
                } while (checkExistCode);
                newContent.ContentCode = code;
                _db.AddToContent(newContent);
                _db.SaveChanges();

                newContent = _db.Content.FirstOrDefault(b => b.ContentCode == newContent.ContentCode);
                ContentDetail detail = new ContentDetail();
                detail.LanguageID = 1;
                detail.ContentID = newContent.ContentID;
                detail.ContentTitle = title.Trim();
                _db.AddToContentDetail(detail);

                string link = string.Empty;
                bool isVertical = false;
                switch (parentCode)
                {
                    case "tu-van":
                        isVertical = false;
                        link = "/TuVan/";
                        break;
                    case "tin-tuc":
                        isVertical = false;
                        link = "/TinTuc/";
                        break;
                    case "hoi-dap":
                        isVertical = false;
                        link = "/HoiDap/";
                        break;
                    case "thiet-ke":
                        isVertical = true;
                        link = "/ThietKe/";
                        break;
                    case "thi-cong":
                        isVertical = true;
                        link = "/ThiCong/";
                        break;
                    case "cung-cap-vlxd":
                        isVertical = true;
                        link = "/CungCapVLXD/";
                        break;
                }
                Menu parentMenu = _db.Menu.FirstOrDefault(b => b.ContentID == parentContent.ContentID);
                Menu newMenu = new Menu();
                newMenu.ParentID = parentMenu.MenuID;
                newMenu.MenuLink = link + code;
                newMenu.ContentID = newContent.ContentID;
                newMenu.IsVertical = isVertical;
                var maxMenu = (from b in _db.Menu
                               where b.ParentID == parentMenu.MenuID
                               select b).Max(b => b.MenuOrder);
                newMenu.MenuOrder = (maxMenu.HasValue ? maxMenu.Value : (-1)) + 1;
                _db.AddToMenu(newMenu);
                _db.SaveChanges();
                newMenu = _db.Menu.FirstOrDefault(b => b.ContentID == newContent.ContentID);
                MenuDetail newMenuDetail = new MenuDetail();
                newMenuDetail.LanguageID = 1;
                newMenuDetail.MenuID = newMenu.MenuID;
                newMenuDetail.MenuTitle = title;
                _db.AddToMenuDetail(newMenuDetail);
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }

        public void UpdateMenu(string code, string newTitle)
        {
            try
            {
                Content content = _db.Content.FirstOrDefault(b => b.ContentCode == code);
                if (content == null)
                    return;
                string newCode = TanHungViet.Helper.Util.GenerateCodeByTitle(newTitle.Trim().ToLower());

                // update content
                ContentRepository contentRepository = new ContentRepository(_db);
                bool checkExistCode = true;
                do
                {
                    Content checkContent = contentRepository.GetContentByCode(newCode);
                    if (checkContent != null)
                    {
                        newCode += "-1";
                        _logger.InfoFormat("New content code is ({0})", newCode);
                    }
                    else
                        checkExistCode = false;
                } while (checkExistCode);
                content.ContentCode = newCode;

                // update content title
                ContentDetail detail = _db.ContentDetail.FirstOrDefault(b => b.ContentID == content.ContentID
                    && b.LanguageID == 1);
                if (detail == null)
                    _logger.WarnFormat("Content co contentID={0} khong ton tai trong ContentDetail table", content.ContentID);
                else
                    detail.ContentTitle = newTitle;

                // update menu
                Menu menu = _db.Menu.FirstOrDefault(b => b.ContentID == content.ContentID);
                if (menu == null)
                {
                    _logger.WarnFormat("Menu co contentID={0} khong ton tai trong Menu table", content.ContentID);
                    return;
                }

                string oldLink = menu.MenuLink;
                int index = oldLink.LastIndexOf("/") + 1;
                string newLink = oldLink.Substring(0, index);
                menu.MenuLink = newLink + newCode;

                // update menu title
                MenuDetail menuDetail = _db.MenuDetail.FirstOrDefault(b => b.MenuID == menu.MenuID
                    && b.LanguageID == 1);
                if (menuDetail == null)
                {
                    _logger.WarnFormat("MenuDetail co menuID={0} khong ton tai trong MenuDetail table", content.ContentID);
                    return;
                }

                menuDetail.MenuTitle = newTitle;

                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw new ArgumentException(ex.Message);
            }
        }
    }
}
